import React, { useEffect, useRef, useState } from 'react';
import ProForm from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { Button, message, Form, Spin, Card } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { getConfig, setConfig } from '@/services/admin/config/config/api';
import CBraftEditor from '@/components/common/CBraftEditor';
interface ValueType {
  content: string;
}
interface PorpsType {
  code: string;
  value: ValueType;
}
const Index: React.FC = () => {
  const formData: PorpsType = {
    code: 'AboutUs',
    value: {
      content: '',
    },
  };
  const restFormRef = useRef<ProFormInstance<ValueType>>();
  const [loading, setLoading] = useState(true);
  const [submitLoading, setSubmitLoading] = useState(true);

  const fetchApi = async () => {
    await setLoading(false);
    const res = await getConfig(formData.code);
    if (res.status == 20000) {
      await restFormRef.current?.setFieldsValue(res.data);
      await setLoading(true);
    }
  };
  useEffect(() => {
    fetchApi();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <PageContainer
      fixedHeader={true}
      title={false}
      footer={[
        <Button
          key={1}
          loading={loading ? false : true}
          onClick={async () => {
            await fetchApi();
          }}
        >
          重置
        </Button>,
        <Button
          key={2}
          type="primary"
          loading={submitLoading ? false : true}
          onClick={() => {
            restFormRef.current?.submit();
          }}
        >
          提交
        </Button>,
      ]}
    >
      <Card>
        <ProForm<ValueType>
          autoFocusFirstInput
          isKeyPressSubmit
          formRef={restFormRef}
          initialValues={formData.value}
          submitter={false}
          onFinish={async (values: any) => {
            await setSubmitLoading(false);
            const res = await setConfig(formData.code, { value: values });
            if (res.status === 20000) {
              message.success(res.message);
            }
            await setSubmitLoading(true);
          }}
        >
          <Spin spinning={loading ? false : true}>
            {loading && (
              <>
                <Form.Item
                  label="关于我们"
                  name="content"
                  rules={[{ required: true, message: '请输入关于我们' }]}
                >
                  <CBraftEditor
                    value={formData.value.content}
                    onChange={async (value: string) => {
                      await restFormRef.current?.setFieldsValue({ content: value });
                    }}
                  />
                </Form.Item>
              </>
            )}
          </Spin>
        </ProForm>
      </Card>
    </PageContainer>
  );
};
export default Index;
